/*
 * @Description: 去接乘客   PickUpPassengers
 * @version: 
 * @Company: 
 * @Author: ZhengZhuang
 * @Date: 2019-08-27 16:53:09
 * @LastAuthor   : zhengzhuang
 * @lastTime     : 2020-01-07 10:25:38
 */
import 'dart:async';

import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/model/itinerary_order_info.dart';
import 'package:C20Driver/provider/order_information.dart';
import 'package:C20Driver/provider/position_information.dart';
import 'package:C20Driver/provider/record_provider.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/utils/locate_info.dart';
import 'package:C20Driver/utils/permission_handler.dart';
import 'package:C20Driver/utils/record_util.dart';
import 'package:C20Driver/utils/utils.dart';
import 'package:provider/provider.dart';
import 'package:C20Driver/routers/navigator_util.dart';

class PickUpPassengers extends StatefulWidget {
  final String orderId;

  PickUpPassengers({this.orderId});

  @override
  _PickUpPassengersState createState() => _PickUpPassengersState();
}

class _PickUpPassengersState extends State<PickUpPassengers> {
  AmapController _amapController;
  Timer _timer;
  Record _record;
  var _countdownTime = 60;

  @override
  void initState() {
    super.initState();

    _getOrderInfo();
    _initRecord();
  }

  /// 获取订单信息
  void _getOrderInfo() {
    Request.getOrderInfo(context: context, orderId: widget.orderId);
  }

  ///初始化录音组件
  void _initRecord() {
    _record = new Record();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<RecordProvider>(builder: (context, recordProvider, _) {
      if (recordProvider.isRecord) {
        Request.receivePassengerFun(context: context, orderId: widget.orderId);
        _record.startRecorder(orderId: widget.orderId);
        _timer = Timer.periodic(Duration(seconds: 1), (timer) {
          if (_countdownTime < 1) {
            _countdownTime = 60;
            _record.stopRecorder();
            Future.delayed(Duration(seconds: 1), () {
              _record.startRecorder(orderId: widget.orderId);
            });
          } else {
            _countdownTime = _countdownTime - 1;
          }
        });
      } else {
        if (_timer != null) {
          if (_timer.isActive) {
            _record.stopRecorder();
            _timer.cancel();
            _timer = null;
          }
        }
      }
      return WillPopScope(
        child: Scaffold(
          appBar: AppBar(
            title: Consumer<OrderInformation>(builder: (context, state, child) {
              String _title = '去接乘客';
              String _status = state.itineraryInfo != null
                  ? state.itineraryInfo.status
                  : '0010';
              switch (_status) {
                case '0010': // 司机接单
                  _title = "去接乘客";
                  break;
                case '0015': // 司机到达上车点
                  _title = "等待乘客上车";
                  break;
                case '0020': // 接到乘客,行程中
                  _title = "行程中";
                  break;
                default:
              }
              return Text(_title != null ? _title : '');
            }),
            actions: <Widget>[
              IconButton(
                iconSize: ScreenUtil().setSp(150.0),
                icon: Text('行程详情'),
                onPressed: () => NavigatorUtil.jump(context,
                    '/detailsOfItineraryOrders?orderId=${widget.orderId}'),
              ),
            ],
          ),
          body: Container(
            child: Stack(
              children: <Widget>[
                _amap(),
                Positioned(
                  top: 0,
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      // 去接乘客顶部显示内容
                      Consumer<OrderInformation>(builder: (ctx, state, child) {
                        return _judgingTopContent(state.itineraryInfo);
                      }),
                      // 路线规划底部操作组件
                      _routePlanningBottom(),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        onWillPop: () => Utils.orderGoHome(context),
      );
    });
  }

  @override
  void dispose() {
    _amapController.dispose();
    // super.dispose();
  }

  Widget _amap() {
    return Consumer<PositionInformation>(builder: (context, model, child) {
      return Container(
        height: double.infinity,
        width: ScreenUtil().setWidth(750.0),
        child: Column(
          children: <Widget>[
            Flexible(
              child: AmapView(
                showZoomControl: false,
                showCompass: true,
                // 中心点坐标
                centerCoordinate:
                    model.driverLocation != null ? model.driverLocation : null,
                // 缩放级别
                onMapCreated: (controller) async {
                  _amapController = controller;
                  if (await PermissionHandlerX.position(context)) {
                    var localtionInfo = await LocateInfo.getLocation(context);
                    if (localtionInfo == null) return;
                  }
                },
                onMapClicked: (latLng) {
                  return;
                },
              ),
            ),
          ],
        ),
      );
    });
  }

  // 顶部内容
  Widget _judgingTopContent(ItineraryOrderInfo data) {
    if (data.status != '0015') {
      // 0010 司机接单
      return _topDistance(data);
    } else {
      return _topWaiting();
    }
  }

  /// 顶部行程中或者实时单中
  Widget _topDistance(ItineraryOrderInfo data) {
    String _targetName;
    String _targetLat;
    String _targetLng;
    switch (data.status) {
      case '0010': // 司机接单
        _targetName = data.depAre;
        _targetLat = data.depLatitude;
        _targetLng = data.depLongitude;
        break;
      case '0015': // 司机到达上车点
        _targetName = data.depAre;
        _targetLat = data.depLatitude;
        _targetLng = data.depLongitude;
        break;
      case '0020': // 接到乘客,行程中
        _targetName = data.destArea;
        _targetLat = data.destLatitude;
        _targetLng = data.destLongitude;

        break;
      default:
    }
    return Container(
      width: ScreenUtil().setWidth(750.0),
      height: ScreenUtil().setWidth(170.0),
      padding: EdgeInsets.only(
        left: ScreenUtil().setWidth(30.0),
        right: ScreenUtil().setWidth(30.0),
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
              width: ScreenUtil().setWidth(1),
              color: Color.fromARGB(255, 215, 215, 215)),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                width: ScreenUtil().setSp(590.0),
                child: Text.rich(
                  TextSpan(
                    text: '去',
                    children: <TextSpan>[
                      TextSpan(
                        text: _targetName,
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(36.0),
                          fontWeight: FontWeight.w700,
                        ),
                      )
                    ],
                  ),
                ),
              ),
              SizedBox(height: ScreenUtil().setWidth(10.0)),
              // Text(
              //   '行程0.2公里8分钟',
              //   style: TextStyle(
              //     fontSize: ScreenUtil().setSp(28.0),
              //     color: Color.fromARGB(255, 102, 102, 102),
              //   ),
              // )
            ],
          ),
          InkWell(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Icon(
                    Icons.navigation,
                    size: ScreenUtil().setWidth(70.0),
                    color: Color.fromARGB(255, 112, 112, 112),
                  ),
                  Text(
                    '导航',
                    style: TextStyle(
                      fontSize: ScreenUtil().setSp(30.0),
                    ),
                  ),
                ],
              ),
              onTap: () => Utils.openGaode(
                  lat: _targetLat,
                  lng: _targetLng,
                  name: _targetName,
                  context: context))
        ],
      ),
    );
  }

  /// 等候乘客上车中
  Widget _topWaiting() {
    return Container(
      width: ScreenUtil().setWidth(750.0),
      height: ScreenUtil().setWidth(90.0),
      padding: EdgeInsets.only(
        left: ScreenUtil().setWidth(30.0),
        right: ScreenUtil().setWidth(30.0),
      ),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            width: ScreenUtil().setWidth(1),
            color: Color.fromARGB(255, 215, 215, 215),
          ),
        ),
      ),
      child: Text(
        '已到达约定上车地点，请等候乘客上车',
        style: TextStyle(
          fontSize: ScreenUtil().setSp(30.0),
        ),
      ),
    );
  }

  Widget _routePlanningBottom() {
    return Column(
      children: <Widget>[
        Container(
          width: ScreenUtil().setWidth(710.0),
          height: ScreenUtil().setWidth(170.0),
          child: Card(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                SizedBox(width: ScreenUtil().setWidth(20.0)),
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    ClipOval(
                      child: Consumer<OrderInformation>(
                          builder: (ctx, state, child) {
                        return Image.network(
                          state.itineraryInfo.passengerHeadimgurl != null
                              ? state.itineraryInfo.passengerHeadimgurl
                              : 'http://apisslcar.liugeche.cn/Data/headImg.png',
                          width: ScreenUtil().setWidth(80.0),
                          height: ScreenUtil().setWidth(80.0),
                          fit: BoxFit.cover,
                        );
                      }),
                    ),
                    Consumer<OrderInformation>(
                        builder: (context, state, child) {
                      return Text(
                        '尾号${state.itineraryInfo.lastNum}',
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(30.0),
                        ),
                      );
                    }),
                  ],
                ),
                SizedBox(width: ScreenUtil().setWidth(20.0)),
                Container(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Container(
                            width: ScreenUtil().setWidth(15.0),
                            height: ScreenUtil().setWidth(15.0),
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              color: Color.fromARGB(255, 36, 142, 247),
                            ),
                          ),
                          SizedBox(width: ScreenUtil().setWidth(10.0)),
                          Container(
                              width: ScreenUtil().setWidth(270.0),
                              child: Consumer<OrderInformation>(
                                  builder: (ctx, state, child) {
                                return Text(
                                  state.itineraryInfo.depAre != null
                                      ? state.itineraryInfo.depAre
                                      : '', // 起点
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setSp(32.0),
                                  ),
                                );
                              })),
                        ],
                      ),
                      SizedBox(height: ScreenUtil().setWidth(10.0)),
                      Row(
                        children: <Widget>[
                          Container(
                            width: ScreenUtil().setWidth(15.0),
                            height: ScreenUtil().setWidth(15.0),
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              color: Color.fromARGB(255, 255, 102, 0),
                            ),
                          ),
                          SizedBox(width: ScreenUtil().setWidth(10.0)),
                          Container(
                              width: ScreenUtil().setWidth(270.0),
                              child: Consumer<OrderInformation>(
                                  builder: (ctx, state, child) {
                                return Text(
                                  state.itineraryInfo.destArea != null
                                      ? state.itineraryInfo.destArea
                                      : '', // 终点
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setSp(32.0),
                                  ),
                                );
                              })),
                        ],
                      )
                    ],
                  ),
                ),
                // IconButton(
                //   icon: Icon(Icons.chat),
                //   onPressed: () =>
                //       NavigatorUtil.jump(context, '/detailsMessage'),
                // ),
                Consumer<OrderInformation>(builder: (ctx, state, child) {
                  return IconButton(
                    icon: Icon(Icons.phone),
                    onPressed: () =>
                        Utils.callPhone(state.itineraryInfo.passengerMobile),
                  );
                })
              ],
            ),
          ),
        ),
        Consumer<OrderInformation>(builder: (ctx, state, child) {
          if (state.itineraryInfo.status != null) {
            return _judgingPullingState(state.itineraryInfo);
          } else {
            return Container();
          }
        })
      ],
    );
  }

  _judgingPullingState(ItineraryOrderInfo info) {
    // 0 为去接乘客 1 为到达约定地点 2 为到达目的地
    if (info.status == '0010') {
      return InkWell(
          child: _buttonText('到达乘客约定地点'),
          onTap: () => Request.driverArriveBoardingPointFun(
              context: context, orderId: widget.orderId));
    }
    if (info.status == '0015') {
      return InkWell(
          child: _buttonText('接到乘客出发'),
          onTap: () {
            Request.queryRecordStatus().then((value) {
              print("queryRecordStatus$value");
              if (value != null) {
                var status = value["status"];

                ///status 0000开启录音，9999关闭录音
                if (status == "0000") {
                  NavigatorUtil.jump(context, '/authorizationRecord');
                } else {
                  Request.receivePassengerFun(
                      context: context, orderId: widget.orderId);
                }
              }
            });
          });
    }
    if (info.status == '0020') {
      return InkWell(
          child: _buttonText('到达目的地'),
          onTap: () {
            print("到达目的地");
            Provider.of<RecordProvider>(context, listen: false).stopRecord();
            Request.orderTripEndFun(context: context, orderId: widget.orderId);
          });
    }
  }

  Widget _buttonText(title) {
    return Container(
      alignment: Alignment.center,
      width: ScreenUtil().setWidth(750.0),
      height: ScreenUtil().setWidth(120.0),
      decoration: BoxDecoration(
        gradient: LinearGradient(colors: [
          Color.fromARGB(255, 255, 103, 27),
          Color.fromARGB(255, 255, 103, 27),
          Color.fromARGB(255, 255, 153, 0),
          Color.fromARGB(255, 255, 153, 0),
        ]),
      ),
      child: Text(
        title,
        style: TextStyle(
          fontSize: ScreenUtil().setSp(36.0),
          color: Colors.white,
        ),
      ),
    );
  }
}
